package com.central.apps.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.img.ImgUtil;
import org.apache.commons.codec.binary.Base64InputStream;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;


public class QRCodeFileUtil {
    /**
     * 图片转化成base64字符串
     * @param imgPath
     * @return
     */
    public static String GetImageStr(String imgPath) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        String imgFile = imgPath;// 待处理的图片
        InputStream in = null;
        byte[] data = null;
        String encode = null; // 返回Base64编码过的字节数组字符串
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        try {
            // 读取图片字节数组
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            encode = encoder.encode(data);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return encode;
    }

    /**
     * base64字符串转化成图片
     *
     * @param imgDatas
     *            图片编码
     * @param imgFilePath
     *            存放到本地路径
     * @return
     * @throws IOException
     */
    @SuppressWarnings("finally")
    public static List<String>  GenerateImage(List<String> imgDatas, String imgFilePath) throws IOException { // 对字节数组字符串进行Base64解码并生成图片
        List<String> fileNames = CollUtil.newArrayList();
        for(int j = 0; j < imgDatas.size(); j++) {
            String imgData = imgDatas.get(j);
            //下面的操作是防止传输过来的数据转译出现问题 报错 Illegal base64 character 3a
            if (imgData.contains("data:")) {
                int start = imgData.indexOf(",");
                imgData = imgData.substring(start + 1);
            }
//            final Base64.Decoder decoder = Base64.getDecoder();
            imgData = imgData.replaceAll("\r|\n", "");
            imgData = imgData.trim();
            byte[] bytes = Base64.getDecoder().decode(imgData); // 将字符串转换为byte数组
            File file = new File(imgFilePath + "/" + j + ".jpg");
            fileNames.add(imgFilePath + "/" + j + ".jpg");
            FileOutputStream  out = null;
            try {
                //转化为输入流
                ByteArrayInputStream in = new ByteArrayInputStream(bytes);

                //写出文件
                byte[] buffer = new byte[1024];

                out = new FileOutputStream(file);

                //写文件
                int len = 0;
                while ((len = in.read(buffer)) != -1) {
                    out.write(buffer, 0, len); // 文件写操作
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                try {
                    if(out != null){
                        out.close();
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return  fileNames;
    }

    public static List<String> createFile(MultipartFile[] fileList, String path) throws Exception {
        List<String> fileNames = CollUtil.newArrayList();
        for(int i = 0; i < fileList.length; i++){
            MultipartFile multipartFile = fileList[i];
            InputStream in = null;
            try {
                in = multipartFile.getInputStream();
                File file = new File(path + "/" + i + ".jpg");
                fileNames.add(path + "/" + i + ".jpg");
                FileOutputStream fout = new FileOutputStream(file);
                int l = -1;
                byte[] tmp = new byte[1024];
                while ((l = in.read(tmp)) != -1) {
                    fout.write(tmp, 0, l);
                    // 注意这里如果用OutputStream.write(buff)的话，图片会失真，大家可以试试
                }
                fout.flush();
                fout.close();
            } catch (Exception e) {
                throw new Exception(e.getMessage());
            } finally {
                // 关闭低层流。
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return fileNames;
    }

//    public static void main(String[] args) throws IOException {
//        String imageStr = FileUtil.GetImageStr("D://下载/企鹅.jpg");
//        System.out.println(imageStr);
//        FileUtil.GenerateImage(imageStr, "D://photos/企鹅.jpg");
//    }
}